import { readFileSync } from 'fs';
import { join } from 'path';
import { request, getOptions, postOptions } from './utils/request';

/**
 * 对象的深度克隆
 * @param {*object} obj 
 */
const clone = (obj) => {
  // Handle the 3 simple types, and null or undefined
  if (null == obj || "object" != typeof obj) return obj;
 
  // Handle Date
  if (obj instanceof Date) {
    const copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }
 
  // Handle Array
  if (obj instanceof Array) {
    const copy = [];
    for (let i = 0; i < obj.length; i++) {
      copy[i] = clone(obj[i]);
    }
    return copy;
  }
 
  // Handle Object
  if (obj instanceof Object) {
    var copy = {};
    for (var attr in obj) {
      if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
    }
    return copy;
  }
 
  throw new Error("Unable to copy obj! Its type isn't supported.");
}

export default function (req, res, next) {
  switch (req.url) {
    case '/api/account/login':
      doapi(req.url, postOptions(req), (data) => {
        // 克隆对象用于返回调用方
        var copy = clone(data);
        if (data.success) {
          var user = data.data;
          user.menus = null; //将菜单信息清除然后保存到session
          req.session.user = user;
        }
        res.send(copy);
      });
      break;
    case '/api/account/logout':
      if (req.session.user) {
        req.body.guid = req.session.user.guid;
        doapi(req.url, postOptions(req), (data) => {
          if (data.success) {
            req.session.user = undefined;
          }
          res.send(data);
        });
      } else {
        res.send({ message: '注销成功.', success: true });
      }
      break;
    case '/api/user/getloginuser':
      if (req.session.user) {
        res.send({ success: true, message: '获取成功!', data: req.session.user });
      } else {
        res.send({ message: '未登录！', success: false });
      }
      break;
    case '/api/article/savearticle':
      if (req.session.user) {
        req.body.UserGuid = req.session.user.userGuid;
        doapi(req.url, postOptions(req), (data) => {
          res.send(data);
        });
      } else {
        res.send({ message: '未登录！', code: -1, success: false });
      }
      break;
    default:
      const user = req.session.user;
      // 如果身份过期则跳转至登录页
      if (user === undefined && req.url.indexOf('/login') === -1) {
        res.redirect(`/login?from=${req.url}`);
      } else {
        if (req.url.indexOf('/api') > -1) {
          if (req.url.indexOf('/login') > -1) {
            res.send({
              statusCode: 401,
              message: '身份过期，请重新登录.',
              success: false,
              data: req.url
            });
            return;
          }
          if (req.method == "POST") {
            doapi(req.url, postOptions(req), (data) => {
              res.send(data);
            });
          }
          if (req.method == "GET") {
            doapi(req.url, getOptions(req), (data) => {
              res.send(data);
            });
          }
        } else {
          next();
        }
      }
      break;
  }
}

function doapi(url, options, callback) {
  request(url, options)
    .then(data => {
      callback(data);
    });
}